package cn.edu.scau.cmi.chenyuesong.hibernate.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.scau.cmi.chenyuesong.hibernate.entity.Teacher;
import cn.edu.scau.cmi.chenyuesong.hibernate.utils.HibernateUtils;

public class TeacherDAO {
private static final Logger log = LoggerFactory.getLogger(TeacherDAO.class);
	
	public void addtea(Teacher teacher){
		log.debug("saving teacher instance");
		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtils.getSession();
			transaction = session.beginTransaction();
			session.save(teacher);
			log.debug("save successful");
			transaction.commit();
		}catch(RuntimeException re) {
			log.error("save failed", re);
			transaction.rollback();
		}
    }
	
	public void deltea(Teacher teacher){
		log.debug("delete teacher instance");
		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtils.getSession();
			transaction = session.beginTransaction();
			session.remove(teacher);
			log.debug("delete successful");
			transaction.commit();
		}catch(RuntimeException re) {
			log.error("delete failed", re);
			transaction.rollback();
		}
    }
	
	public void updtea(Teacher teacher){
		log.debug("update teacher instance");
		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtils.getSession();
			transaction = session.beginTransaction();
			session.update(teacher);
			log.debug("update successful");
			transaction.commit();
		}catch(RuntimeException re) {
			log.error("update failed", re);
			transaction.rollback();
		}
    }
	
	public List<Teacher> getAllTea() {
		List<Teacher> teachers = new ArrayList<Teacher>();
		log.debug("get all teacher");
		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtils.getSession();
			transaction = session.beginTransaction();
			Query query = session.createQuery("from Teacher");
			teachers = query.list();
			log.debug("get all teacher successful");
			transaction.commit();
		}catch(RuntimeException re) {
			log.error("get all teacher failed", re);
			transaction.rollback();
		}
		return teachers;
	}
	
	public Teacher getTea(Integer id) {
		log.debug("get teacher");
		Teacher teacher = new Teacher();
		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtils.getSession();
			transaction = session.beginTransaction();
			teacher = (Teacher) session.get("cn.edu.scau.cmi.cheyuesong.hibernate.entity.Teacher",id);
			log.debug("get teacher successful");
			transaction.commit();
		}catch(RuntimeException re) {
			log.error("get teacher failed", re);
			transaction.rollback();
		}
		return teacher;
	}
}
